package com.boolib.commons.exception;


import com.boolib.commons.Const;
import com.boolib.commons.aop.exception.child.UserIsNotLoginException;
import com.boolib.commons.entity.ServerResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {


    @ExceptionHandler(BindException.class)
    public ServerResponse<String> bindException(BindException ex){
        List<ObjectError> errorList = ex.getAllErrors();
        return ServerResponse.createByError(10,errorList.get(0).getDefaultMessage());
    }

    @ExceptionHandler(UserIsNotLoginException.class)
    public ServerResponse<String> UserAuthException(UserIsNotLoginException ex){
        return ServerResponse.createByError(Const.System.Status.UNAUTHENTICATION.getCode(),Const.System.Status.UNAUTHENTICATION.getMessage());
    }


    @ExceptionHandler( SQLIntegrityConstraintViolationException.class)
    public ServerResponse<String> UserAuthException(SQLIntegrityConstraintViolationException ex){
        return ServerResponse.createByError(Const.System.Status.EXIST.getCode(),Const.System.Status.EXIST.getMessage());
    }
}
